package com.mvvmhabit.org.binding.viewadapter.banner

import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.mvvmhabit.org.base.BaseBannerEntity
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.utils.ScreenUtil
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.RectangleIndicator
import com.youth.banner.listener.OnBannerListener
import com.youth.banner.util.BannerUtils

// banner 的相关操作
@BindingAdapter(
    value = ["bannerAdapter", "bannerData", "onClickBannerItemCommand"],
    requireAll = false
)
fun <T> setBannerAdapter(
    banner: Banner<T, BannerAdapter<T, BannerImageHolder>>?,
    bannerAdapter: BannerAdapter<T, BannerImageHolder>?,
    bannerData: List<T>?,
    onClickBannerItemCommand: BindingCommand<T>?
) {
    if (bannerAdapter == null) {
        // 设置adapter
        banner?.setAdapter(object : BannerImageAdapter<T>(bannerData) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: T,
                position: Int,
                size: Int
            ) {
                holder!!.imageView.scaleType = ImageView.ScaleType.FIT_XY
                Glide.with(holder.imageView.context)
                    .load((data as BaseBannerEntity).pictureAddr)
                    .into(holder.imageView)
            }
        }, true)
    } else {
        val adapter = banner?.adapter
        if (adapter == null) {
            bannerAdapter.setDatas(bannerData)
            banner?.setAdapter(bannerAdapter)
        } else {
            adapter.setDatas(bannerData)
        }
    }
    banner?.indicator = RectangleIndicator(banner?.context)
    banner?.indicatorConfig
        ?.setNormalColor(0x4DFFFFFF)
        ?.setSelectedColor(-0x1)?.selectedWidth = ScreenUtil.dp2px(banner?.context, 10f)
    banner?.setIndicatorSpace(BannerUtils.dp2px(6f).toInt())
    banner?.setOnBannerListener(object : OnBannerListener<T> {
        override fun OnBannerClick(data: T, position: Int) {
            onClickBannerItemCommand?.execute(data)
        }
    })
}

